package controllers

import (
	"gin-AssetManagement/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token, err := c.Cookie("cookie")
		if err != nil || token == "" {
			// 如果 cookie 不存在或为空，则跳转到登录页面
			c.Redirect(http.StatusFound, "/login")
			c.Abort() // 终止请求链
			return
		}
		myclaims, err := utils.ParseTokenHs256(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, Respond{
				Code: 1,
				Msg:  err.Error(),
				Data: "错误",
			})
			c.Abort()
			return
		}
		url := c.Request.URL.Path
		requestType := c.Request.Method
		if enforce := utils.IsRolesAcl(*myclaims, url, requestType); enforce == false {
			c.HTML(http.StatusUnauthorized, "error/error.html", nil)
			c.Abort()
		}
		c.Set("userID", myclaims.UserId)
		c.Set("username", myclaims.Username)
		c.Next()
	}
}
